import 'package:flutter/material.dart';
import 'package:flutter_smart_heating/ui/ui.dart';

class UiSearchBar extends StatefulWidget {
  const UiSearchBar({
    super.key,
    this.render = false,
    this.controller,
    this.placeholder = '请输入关键词',
    this.height = 40,
    this.backgroundColor,
    this.borderRadius,
    this.icon,
    this.clearable = true,
    this.autofocus = false,
    this.onChanged,
    this.onSubmitted,
    this.onClear,
  });

  final bool render;

  final UiSearchBarController? controller;

  /// 左侧图标
  final Widget? icon;

  final BorderRadius? borderRadius;

  /// 输入框高度
  final double height;

  /// 占位符
  final String placeholder;

  /// 背景颜色
  final Color? backgroundColor;

  /// 自动聚焦
  final bool autofocus;

  /// 显示清空按钮
  final bool clearable;

  /// 输入值改变
  final Function(String)? onChanged;

  /// 输入框提交
  final Function(String)? onSubmitted;

  /// 清空输入框
  final Function()? onClear;

  @override
  State<UiSearchBar> createState() => UiSearchBarState();
}

class UiSearchBarState extends State<UiSearchBar> {
  TextEditingController controller = TextEditingController();
  FocusNode focusNode = FocusNode();
  String keyword = '';
  bool isReady = false;
  @override
  void initState() {
    widget.controller?.bind(this);
    isReady = widget.render;
    super.initState();
  }

  void setValue(Function() fn) {
    setState(fn);
  }

  @override
  Widget build(BuildContext context) {
    Ui.onPageAnimateCompleted(context, () {
      setState(() {
        isReady = true;
      });
    });
    return UiPanel(
      height: widget.height,
      borderRadius: widget.borderRadius,
      backgroundColor: widget.backgroundColor,
      child: Row(
        children: [
          const SizedBox(width: 12),
          widget.icon ??
              const UiIcon(
                UiIcons.search_short,
                color: Colors.grey,
                size: 19,
              ),
          const SizedBox(width: 5),
          Expanded(
            child: isReady
                ? UiInput(
                    controller: controller,
                    focusNode: focusNode,
                    placeholder: widget.placeholder,
                    autofocus: widget.autofocus,
                    onSubmitted: (value) {
                      setState(() {
                        keyword = value;
                      });
                      widget.onSubmitted?.call(keyword);
                    },
                    onChanged: (value) {
                      setState(() {
                        keyword = value;
                      });
                      widget.onChanged?.call(keyword);
                    },
                  )
                : Text(
                    widget.placeholder,
                    style: TextStyle(
                      color: UiTheme(context).infoColor,
                      fontSize: 15,
                    ),
                  ),
          ),
          AnimatedSwitcher(
            duration: kThemeAnimationDuration,
            child: widget.clearable && keyword.isNotEmpty
                ? IconButton(
                    onPressed: () {
                      controller.clear();
                      setState(() {
                        keyword = '';
                      });
                      widget.onClear?.call();
                    },
                    icon: CircleAvatar(
                      backgroundColor: Colors.grey[500],
                      radius: 10,
                      child: const Icon(
                        Icons.close,
                        size: 14,
                        color: Colors.white,
                      ),
                    ),
                  )
                : Container(),
          )
        ],
      ),
    );
  }
}

class UiSearchBarController {
  late UiSearchBarState state;
  bool initialized = false;
  bind(UiSearchBarState uiSearchBarState) {
    state = uiSearchBarState;
    initialized = true;
  }

  String get value {
    return state.keyword;
  }

  set value(val) {
    state.setValue(() {
      state.keyword = val;
    });
    state.controller.value = TextEditingValue(text: val);
  }

  bool get hasFocus {
    return initialized ? state.focusNode.hasFocus : false;
  }

  unfocus() {
    state.focusNode.unfocus();
  }

  requestFocus() {
    state.focusNode.requestFocus();
  }
}
